#include <QCoreApplication>

#include <rpc/xdr.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <iostream>

#include "request.h"

using namespace std;

char *encode(struct request *req, size_t *sizep)
{
    char *buf = NULL;
    FILE *fp = open_memstream(&buf, sizep);

    XDR xdr;
    xdrstdio_create(&xdr, fp, XDR_ENCODE);

    bool_t ret = xdr_request(&xdr, req);
    fclose(fp);

    return buf;
}

void decode(char *buf, int size, struct request *req)
{
    FILE *fp = fmemopen(buf, size, "r");

    XDR xdr;
    xdrstdio_create(&xdr, fp, XDR_DECODE);

    bool_t ret = xdr_request(&xdr, req);

    fclose(fp);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    struct request req;
    strcpy(req.session_id, "adbc2021");
    strcpy(req.name, "Jimmy");
    strcpy(req.data, "hello, world!");
    req.data_len = strlen("hello, world!") + 1;

    char *buf = NULL;
    size_t size = 0;
    buf = encode(&req, &size);
    cout << "buffer size after encode: " << size << endl;

    struct request _req;
    decode(buf, size, &_req);
    cout << "decoded seedion_id: " << _req.session_id << endl;
    cout << "decoded name: " << _req.name << endl;
    cout << "decoded data: " << _req.data << endl;
    cout << "decoded data_len: " << _req.data_len << endl;

    free(buf);

    return a.exec();
}
